package com.money.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.domain.po.UserMoney;
import com.money.mapper.UserMoneyMapper;
import com.money.service.UserMoneyService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.session.SqlSession;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.function.BiConsumer;

/**
 * @author 路亚
 * @version 0.1
 * @className UserMoneyServiceImpl
 * @description
 * @date 2024/12/27 16:30
 * @since jdk11
 */
@Service
@RequiredArgsConstructor
public class UserMoneyServiceImpl extends ServiceImpl<UserMoneyMapper, UserMoney> implements UserMoneyService {

    private final ThreadPoolTaskExecutor taskExecutor;

    @Override
    public void turnMoney() {
        QueryWrapper<UserMoney> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("gold_num", 100);
        List<UserMoney> list = list();
        CountDownLatch countDownLatch = new CountDownLatch(list.size());
        for (UserMoney userMoney : list) {
            taskExecutor.execute(() -> {
                Integer addMoney = userMoney.getGoldNum() / 100;
                userMoney.setRealMoney(userMoney.getRealMoney() + addMoney);
                userMoney.setGoldNum(userMoney.getGoldNum() - addMoney * 100);
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        taskExecutor.shutdown();
        this.executeBatch(list, new BiConsumer<SqlSession, UserMoney>() {
            @Override
            public void accept(SqlSession sqlSession, UserMoney userMoney) {
                UserMoneyMapper mapper = sqlSession.getMapper(UserMoneyMapper.class);
                mapper.goldToMoney(userMoney);
            }
        });
    }
}
